// electron-main/index.ts
import { app, BrowserWindow , Tray , Menu , nativeImage} from "electron";
import path from "path";

let win : BrowserWindow
let tray
const createWindow = () => {
    win = new BrowserWindow({
        webPreferences: {
            contextIsolation: false, // 是否开启隔离上下文
            nodeIntegration: true, // 渲染进程使用Node API
            preload: path.join(__dirname, "../electron-preload/index.js"), // 需要引用js文件
        },
    });

    Menu.setApplicationMenu(null);
    // 如果打包了，渲染index.html
    if (app.isPackaged) {
        win.loadFile(path.join(__dirname, "../index.html"));
    } else {
        let url = "http://localhost:80"; // 本地启动的vue项目路径
        win.loadURL(url);
    }

    win.on('close', () => {

    });

    win.on('ready-to-show' , () => {
        win.show()
    });

    win.on('closed' , () => {

    });

    tray = new Tray(nativeImage.createFromPath(path.join(__dirname , 'dist/vite.svg')))
    //菜单
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '显示',
            click: () => {
                win.show()
                app.focus()
            }
        },
        {
            label: '退出',
            click: () => {
                win.destroy()
            }
        }
    ]);
    tray.setContextMenu(contextMenu);
    tray.setToolTip('sam process')
    tray.setTitle('sam')
};


app.whenReady().then(() => {
    createWindow(); // 创建窗口
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});


// 关闭窗口
app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
});
